package com.kly.springbootinit.controller;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.kly.springbootinit.common.BaseResponse;
import com.kly.springbootinit.common.ErrorCode;
import com.kly.springbootinit.common.ResultUtils;
import com.kly.springbootinit.exception.ThrowUtils;
import com.kly.springbootinit.model.dto.payment.PaymentAddRequest;
import com.kly.springbootinit.model.dto.payment.PaymentQueryRequest;
import com.kly.springbootinit.model.entity.Payment;
import com.kly.springbootinit.model.entity.User;
import com.kly.springbootinit.model.vo.PaymentVO;
import com.kly.springbootinit.service.PaymentService;
import com.kly.springbootinit.service.UserService;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @author admin
 * @date 2025/5/22
 */
@RestController
@RequestMapping("/payments")
public class PaymentController {

    @Resource
    private PaymentService paymentService;

    @Resource
    private UserService userService;


    /**
     * 创建支付记录
     */
    @PostMapping
    public BaseResponse<PaymentVO> createPayment(@RequestBody PaymentAddRequest paymentAddRequest) {
        ThrowUtils.throwIf(paymentAddRequest == null, ErrorCode.PARAMS_ERROR);
        return ResultUtils.success(paymentService.createPayment(paymentAddRequest));
    }

    /**
     * 支付订单
     */
    @PutMapping("/{id}")
    public BaseResponse<PaymentVO> payPayment(@PathVariable("id") Long id, String payMethod) {
        ThrowUtils.throwIf(id == null, ErrorCode.PARAMS_ERROR);
        return ResultUtils.success(paymentService.payPayment(id, payMethod));
    }

    /**
     * 查询支付记录
     */
    @GetMapping
    public BaseResponse<PaymentVO> getPayment(Long id) {
        ThrowUtils.throwIf(id == null, ErrorCode.PARAMS_ERROR);
        Payment payment = paymentService.getById(id);
        ThrowUtils.throwIf(payment == null, ErrorCode.PARAMS_ERROR, "支付记录不存在");
        PaymentVO paymentVO = BeanUtil.copyProperties(payment, PaymentVO.class);
        User user = userService.getById(paymentVO.getUserId());
        paymentVO.setUser(userService.getUserVO(user));
        return ResultUtils.success(paymentVO);
    }

    /**
     * 查询支付列表
     */
    @GetMapping("/list")
    public BaseResponse<Page<PaymentVO>> getPaymentList(PaymentQueryRequest paymentQueryRequest) {
        ThrowUtils.throwIf(paymentQueryRequest == null, ErrorCode.PARAMS_ERROR);
        Long id = paymentQueryRequest.getId();
        Long orderId = paymentQueryRequest.getOrderId();
        Long userId = paymentQueryRequest.getUserId();
        BigDecimal amount = paymentQueryRequest.getAmount();
        String paymentMethod = paymentQueryRequest.getPaymentMethod();
        Integer status = paymentQueryRequest.getStatus();
        int current = paymentQueryRequest.getCurrent();
        int pageSize = paymentQueryRequest.getPageSize();


        Page<Payment> paymentPage = paymentService.lambdaQuery()
                .eq(id != null, Payment::getId, id)
                .eq(orderId != null, Payment::getOrderId, orderId)
                .eq(userId != null, Payment::getUserId, userId)
                .eq(amount != null, Payment::getAmount, amount)
                .eq(paymentMethod != null, Payment::getPaymentMethod, paymentMethod)
                .eq(status != null, Payment::getStatus, status)
                .page(new Page<>(current, pageSize));

        Page<PaymentVO> paymentVOPage = new Page<>(current, pageSize, paymentPage.getTotal());
        List<Payment> records = paymentPage.getRecords();
        if (CollUtil.isEmpty(records)) {
            return ResultUtils.success(paymentVOPage);
        }
        List<PaymentVO> paymentVOList = BeanUtil.copyToList(records, PaymentVO.class);
        // 获取用户信息paymentVOList
        Set<Long> userIdList = paymentVOList.stream().map(PaymentVO::getUserId).collect(Collectors.toSet());
        Map<Long, List<User>> userIdUserMap = userService.listByIds(userIdList).stream().collect(Collectors.groupingBy(User::getId));
        paymentVOList = paymentVOList.stream().map(paymentVO -> {
            Long userId1 = paymentVO.getUserId();
            User user = null;
            if (userIdUserMap.containsKey(userId1)) {
                user = userIdUserMap.get(userId1).get(0);
            }
            paymentVO.setUser(userService.getUserVO(user));
            return paymentVO;
        }).collect(Collectors.toList());
        paymentVOPage.setRecords(paymentVOList);
        return ResultUtils.success(paymentVOPage);
    }


}
